package 删除链表的倒数第N个结点;

import 两两交换链表中的节点.Demo24;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 删除链表的倒数第 N 个结点,删除倒数第几个以及环状链表最好使用双指针的快慢指针实现
 * @date 2022/10/15 15:07
 */
public class Demo19 {
    /**
     * Definition for singly-linked list.
     *
     * */
    public class ListNode {
        int val;
         ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre=new ListNode(-1);
        pre.next=head;
        ListNode slow=pre;
        ListNode fast=pre;
        int length=0;
        while (length<n){
            fast=fast.next;
            length++;
        }
        //快慢指针一起移动，当快指针移动到最后了
        while (fast!=null&&fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        //slow的下一个节点就要删除了
        slow.next=slow.next.next;
        return pre.next;
    }
}
